#!/bin/bash

# AI Booster 一键安装配置脚本
# 作者: Administrator
# 用途: 在任何Linux系统上一键配置科学上网功能
# 使用方法: sudo bash install_ai_booster.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查root权限
check_root() {
    if [ "$EUID" -ne 0 ]; then
        print_error "请使用root权限运行此脚本: sudo bash $0"
        exit 1
    fi
}

# 检测系统类型
detect_system() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
    elif type lsb_release >/dev/null 2>&1; then
        OS=$(lsb_release -si)
        VER=$(lsb_release -sr)
    elif [ -f /etc/lsb-release ]; then
        . /etc/lsb-release
        OS=$DISTRIB_ID
        VER=$DISTRIB_RELEASE
    elif [ -f /etc/debian_version ]; then
        OS=Debian
        VER=$(cat /etc/debian_version)
    elif [ -f /etc/SuSe-release ]; then
        OS=openSUSE
    elif [ -f /etc/redhat-release ]; then
        OS=RedHat
    else
        OS=$(uname -s)
        VER=$(uname -r)
    fi
    
    print_info "检测到系统: $OS $VER"
}

# 备份现有配置
backup_existing() {
    local backup_dir="/opt/ai_booster_backup_$(date +%Y%m%d_%H%M%S)"
    
    if [ -f "/etc/ai_booster" ]; then
        print_warning "发现现有的ai_booster配置，正在备份..."
        mkdir -p "$backup_dir"
        cp /etc/ai_booster "$backup_dir/" 2>/dev/null || true
        print_info "现有配置已备份到: $backup_dir"
    fi
}

# 创建ai_booster主脚本
create_ai_booster_script() {
    print_info "正在创建 /etc/ai_booster 脚本..."
    
    cat > /etc/ai_booster << 'EOF'
#! /bin/bash

function enable() {
    if [ "$PUHUI_SMARTML_PROXY" == "none" ];then
        echo "当前区域不支持科学加速，设置不生效"
        return 0
    fi
    export no_proxy=localhost,127.0.0.1,modelscope.com,aliyuncs.com,tencentyun.com,wisemodel.cn,edu.cn,aliyun.com,douban.com,tencent.com,163.com,google.com,baidu.com,sohu.com
    if [ -z "$PUHUI_SMARTML_PROXY_HTTP" ];then
      export http_proxy=http://10.205.32.239:9090
      export https_proxy=http://10.205.32.239:9090
    else
      export http_proxy=http://$PUHUI_SMARTML_PROXY_HTTP
      export https_proxy=http://$PUHUI_SMARTML_PROXY_HTTP
    fi

    if ! grep -q 'source /etc/ai_booster enable' /root/.bashrc ;then
      echo >> /root/.bashrc
      echo "source /etc/ai_booster enable" >> /root/.bashrc
    fi
    echo '设置成功'
    echo '注意：仅限于AI研究，如果无法使用，请客服群进行反馈。'
}

function disable() {
    unset no_proxy
    unset http_proxy
    unset https_proxy
    sed -i '/^source \/etc\/ai_booster enable$/d' ~/.bashrc > /dev/null 2>&1
    sed -i '/^source \/etc\/ai_booster enable$/d' /root/.bashrc > /dev/null 2>&1
    echo '科学上网已禁用'
}

function status() {
    if [ -n "$http_proxy" ] || [ -n "$https_proxy" ]; then
        echo "科学上网状态: 已启用"
        echo "HTTP代理: $http_proxy"
        echo "HTTPS代理: $https_proxy"
        echo "忽略代理: $no_proxy"
    else
        echo "科学上网状态: 已禁用"
    fi
}

case $1 in
  enable)
    enable
    ;;
  disable)
    disable
    ;;
  status)
    status
    ;;
  *)
    echo "使用方法: source /etc/ai_booster {enable|disable|status}"
    echo ""
    echo "命令说明:"
    echo "  enable  - 启用科学上网"
    echo "  disable - 禁用科学上网"
    echo "  status  - 查看当前状态"
    ;;
esac
EOF

    chmod +x /etc/ai_booster
    print_success "ai_booster脚本创建完成"
}

# 设置环境变量
setup_environment() {
    print_info "正在配置环境变量..."
    
    # 设置代理服务器地址环境变量
    if ! grep -q "PUHUI_SMARTML_PROXY_HTTP" /etc/environment; then
        echo "PUHUI_SMARTML_PROXY_HTTP=10.205.32.239:9090" >> /etc/environment
    fi
    
    print_success "环境变量配置完成"
}

# 创建profile.d脚本
setup_profile_scripts() {
    print_info "正在配置profile.d脚本..."
    
    # 创建locale-fix脚本
    cat > /etc/profile.d/01-locale-fix.sh << 'EOF'
# Make sure the locale variables are set to valid values.
eval $(/usr/bin/locale-check C.UTF-8) 2>/dev/null || true
EOF

    # 创建smartml脚本
    cat > /etc/profile.d/999-smartml.sh << 'EOF'
#!/bin/sh
alias sudo=""
EOF

    chmod +x /etc/profile.d/01-locale-fix.sh
    chmod +x /etc/profile.d/999-smartml.sh
    
    print_success "profile.d脚本配置完成"
}

# 创建便捷命令别名
create_aliases() {
    print_info "正在创建便捷命令别名..."
    
    # 为root用户创建别名
    if ! grep -q "alias ai-enable" /root/.bashrc; then
        cat >> /root/.bashrc << 'EOF'

# AI Booster 便捷命令
alias ai-enable='source /etc/ai_booster enable'
alias ai-disable='source /etc/ai_booster disable'
alias ai-status='source /etc/ai_booster status'
EOF
    fi
    
    # 为所有用户创建全局别名
    cat > /etc/profile.d/99-ai-booster-aliases.sh << 'EOF'
#!/bin/bash
# AI Booster 全局别名
alias ai-enable='source /etc/ai_booster enable'
alias ai-disable='source /etc/ai_booster disable'
alias ai-status='source /etc/ai_booster status'
EOF
    
    chmod +x /etc/profile.d/99-ai-booster-aliases.sh
    
    print_success "便捷命令别名创建完成"
}

# 创建卸载脚本
create_uninstall_script() {
    print_info "正在创建卸载脚本..."
    
    cat > /usr/local/bin/uninstall_ai_booster.sh << 'EOF'
#!/bin/bash

echo "正在卸载 AI Booster..."

# 禁用代理
source /etc/ai_booster disable 2>/dev/null || true

# 删除主脚本
rm -f /etc/ai_booster

# 删除profile.d脚本
rm -f /etc/profile.d/01-locale-fix.sh
rm -f /etc/profile.d/999-smartml.sh
rm -f /etc/profile.d/99-ai-booster-aliases.sh

# 清理bashrc中的配置
sed -i '/^source \/etc\/ai_booster enable$/d' /root/.bashrc 2>/dev/null || true
sed -i '/# AI Booster 便捷命令/,+3d' /root/.bashrc 2>/dev/null || true

# 清理环境变量
sed -i '/PUHUI_SMARTML_PROXY_HTTP/d' /etc/environment 2>/dev/null || true

# 删除卸载脚本自身
rm -f /usr/local/bin/uninstall_ai_booster.sh

echo "AI Booster 已完全卸载"
EOF

    chmod +x /usr/local/bin/uninstall_ai_booster.sh
    print_success "卸载脚本创建完成: /usr/local/bin/uninstall_ai_booster.sh"
}

# 测试安装
test_installation() {
    print_info "正在测试安装..."
    
    if [ -f "/etc/ai_booster" ] && [ -x "/etc/ai_booster" ]; then
        print_success "ai_booster脚本安装成功"
    else
        print_error "ai_booster脚本安装失败"
        return 1
    fi
    
    # 测试命令
    print_info "测试基本功能..."
    source /etc/ai_booster status
    
    print_success "安装测试完成"
}

# 显示使用说明
show_usage() {
    echo ""
    echo "========================================="
    echo "     AI Booster 安装完成!"
    echo "========================================="
    echo ""
    echo "使用方法:"
    echo "  启用科学上网: source /etc/ai_booster enable"
    echo "                或者: ai-enable"
    echo ""
    echo "  禁用科学上网: source /etc/ai_booster disable" 
    echo "                或者: ai-disable"
    echo ""
    echo "  查看状态:     source /etc/ai_booster status"
    echo "                或者: ai-status"
    echo ""
    echo "卸载方法:"
    echo "  sudo /usr/local/bin/uninstall_ai_booster.sh"
    echo ""
    echo "注意事项:"
    echo "  - 仅限于AI研究使用"
    echo "  - 如遇问题请联系客服群反馈"
    echo "  - 重启终端或重新登录以使别名生效"
    echo ""
    echo "========================================="
}

# 主函数
main() {
    echo "========================================="
    echo "     AI Booster 一键安装脚本"
    echo "========================================="
    echo ""
    
    check_root
    detect_system
    backup_existing
    
    print_info "开始安装 AI Booster..."
    
    create_ai_booster_script
    setup_environment
    setup_profile_scripts
    create_aliases
    create_uninstall_script
    test_installation
    
    show_usage
    
    print_success "AI Booster 安装完成！"
    print_warning "请重启终端或重新登录以使所有配置生效"
}

# 运行主函数
main "$@"
